package com.tenton.utils;

/**
 * @ClassName: Crc16Util
 * @Description： CRC计算
 * @Author： tangdong
 * @Date： 2024/6/25
 */
public class Crc16Util {
    static short[] Table_CRC = new short[256];

    public static short crc_16(byte[] data) {

        createCRC16Table((short) 0x8005);
        short nAccum = (short) 0xFFFF;
        int shortMask = 0xffff;
        int byteMask = 0xffffff;
        for (int i = 0; i < data.length; i++) {
            byte thisData = ByteUtil.byte2Unsigned(data[i]);
            byte t = Integer.valueOf((nAccum >> 8)).byteValue();
            byte index = Integer.valueOf((t ^ thisData) & byteMask).byteValue();
            nAccum = Integer.valueOf(((nAccum << 8) ^ Table_CRC[Byte.toUnsignedInt(index)]) & shortMask).shortValue();
        }
        //按位取反 20220605 新增
        nAccum = (short) ~nAccum;
        return nAccum;
    }

    private static void createCRC16Table(short aPoly) {
        short nData;
        short nAccum;
        for (short i = 0; i < 256; i++) {
            nData = (short) (i << 8);
            nAccum = 0;
            for (short j = 0; j < 8; j++) {
                if (((nData ^ nAccum) & 0x8000) != 0)
                    nAccum = (short) ((nAccum << 1) ^ aPoly);
                else
                    nAccum <<= 1;
                nData <<= 1;
            }
            Table_CRC[i] = nAccum;
        }
    }

}
